using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;

namespace PackTracker.Business
{ 
	[Serializable()] 
	public class Funcionario : Csla.BusinessBase<Funcionario>
	{
		#region Business Properties and Methods

		//declare members
		private int _id = 0;
		private string _nome = string.Empty;
		private int _telefone = 0;
		private string _rg = string.Empty;
		private string _cpf = string.Empty;
		private string _habilitacao = string.Empty;
		private string _matricula = string.Empty;
		private int _idUsuario = 0;

		//declare borrowed child member(s)
		private string _idUsuarioLogin;

		[System.ComponentModel.DataObjectField(true, true)]
		public int Id
		{
			get
			{
				CanReadProperty("Id", true);
				return _id;
			}
		}

		public string Nome
		{
			get
			{
				CanReadProperty("Nome", true);
				return _nome;
			}
			set
			{
				CanWriteProperty("Nome", true);
				if (value == null) value = string.Empty;
				if (!_nome.Equals(value))
				{
					_nome = value;
					PropertyHasChanged("Nome");
				}
			}
		}

		public int Telefone
		{
			get
			{
				CanReadProperty("Telefone", true);
				return _telefone;
			}
			set
			{
				CanWriteProperty("Telefone", true);
				if (!_telefone.Equals(value))
				{
					_telefone = value;
					PropertyHasChanged("Telefone");
				}
			}
		}

		public string Rg
		{
			get
			{
				CanReadProperty("Rg", true);
				return _rg;
			}
			set
			{
				CanWriteProperty("Rg", true);
				if (value == null) value = string.Empty;
				if (!_rg.Equals(value))
				{
					_rg = value;
					PropertyHasChanged("Rg");
				}
			}
		}

		public string Cpf
		{
			get
			{
				CanReadProperty("Cpf", true);
				return _cpf;
			}
			set
			{
				CanWriteProperty("Cpf", true);
				if (value == null) value = string.Empty;
				if (!_cpf.Equals(value))
				{
					_cpf = value;
					PropertyHasChanged("Cpf");
				}
			}
		}

		public string Habilitacao
		{
			get
			{
				CanReadProperty("Habilitacao", true);
				return _habilitacao;
			}
			set
			{
				CanWriteProperty("Habilitacao", true);
				if (value == null) value = string.Empty;
				if (!_habilitacao.Equals(value))
				{
					_habilitacao = value;
					PropertyHasChanged("Habilitacao");
				}
			}
		}

		public string Matricula
		{
			get
			{
				CanReadProperty("Matricula", true);
				return _matricula;
			}
			set
			{
				CanWriteProperty("Matricula", true);
				if (value == null) value = string.Empty;
				if (!_matricula.Equals(value))
				{
					_matricula = value;
					PropertyHasChanged("Matricula");
				}
			}
		}

		public int IdUsuario
		{
			get
			{
				CanReadProperty("IdUsuario", true);
				return _idUsuario;
			}
			set
			{
				CanWriteProperty("IdUsuario", true);
				if (!_idUsuario.Equals(value))
				{
					_idUsuario = value;
					PropertyHasChanged("IdUsuario");
				}
			}
		}

		public string idUsuarioLogin
		{
			get
			{
				CanReadProperty("idUsuarioLogin", true);
				return _idUsuarioLogin;
			}
		}
 
		protected override object GetIdValue()
		{
			return _id;
		}

		#endregion //Business Properties and Methods

		#region Validation Rules
		private void AddCustomRules()
		{
			//add custom/non-generated rules here...
		}

		private void AddCommonRules()
		{
			//
			// Nome
			//
			ValidationRules.AddRule(CommonRules.StringRequired, "Nome");
			ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("Nome", 50));
			//
			// Rg
			//
			ValidationRules.AddRule(CommonRules.StringRequired, "Rg");
			ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("Rg", 9));
			//
			// Cpf
			//
			ValidationRules.AddRule(CommonRules.StringRequired, "Cpf");
			ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("Cpf", 11));
			//
			// Habilitacao
			//
			ValidationRules.AddRule(CommonRules.StringRequired, "Habilitacao");
			ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("Habilitacao", 10));
			//
			// Matricula
			//
			ValidationRules.AddRule(CommonRules.StringRequired, "Matricula");
			ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("Matricula", 15));
			//
			// IdUsuario
			//
			ValidationRules.AddRule(CommonRules.IntegerMinValue, new CommonRules.IntegerMinValueRuleArgs("IdUsuario", 1));
		}

		protected override void AddBusinessRules()
		{
			AddCommonRules();
			AddCustomRules();
		}
		#endregion //Validation Rules

		#region Authorization Rules
		protected override void AddAuthorizationRules()
		{
			//TODO: Define authorization rules in Funcionario
			//AuthorizationRules.AllowRead("Id", "FuncionarioReadGroup");
			//AuthorizationRules.AllowRead("Nome", "FuncionarioReadGroup");
			//AuthorizationRules.AllowRead("Telefone", "FuncionarioReadGroup");
			//AuthorizationRules.AllowRead("Rg", "FuncionarioReadGroup");
			//AuthorizationRules.AllowRead("Cpf", "FuncionarioReadGroup");
			//AuthorizationRules.AllowRead("Habilitacao", "FuncionarioReadGroup");
			//AuthorizationRules.AllowRead("Matricula", "FuncionarioReadGroup");
			//AuthorizationRules.AllowRead("IdUsuario", "FuncionarioReadGroup");

			//AuthorizationRules.AllowWrite("Nome", "FuncionarioWriteGroup");
			//AuthorizationRules.AllowWrite("Telefone", "FuncionarioWriteGroup");
			//AuthorizationRules.AllowWrite("Rg", "FuncionarioWriteGroup");
			//AuthorizationRules.AllowWrite("Cpf", "FuncionarioWriteGroup");
			//AuthorizationRules.AllowWrite("Habilitacao", "FuncionarioWriteGroup");
			//AuthorizationRules.AllowWrite("Matricula", "FuncionarioWriteGroup");
			//AuthorizationRules.AllowWrite("IdUsuario", "FuncionarioWriteGroup");
		}


		public static bool CanGetObject()
		{
			//TODO: Define CanGetObject permission in Funcionario
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("FuncionarioViewGroup"))
			//	return true;
			//return false;
		}

		public static bool CanAddObject()
		{
			//TODO: Define CanAddObject permission in Funcionario
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("FuncionarioAddGroup"))
			//	return true;
			//return false;
		}

		public static bool CanEditObject()
		{
			//TODO: Define CanEditObject permission in Funcionario
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("FuncionarioEditGroup"))
			//	return true;
			//return false;
		}

		public static bool CanDeleteObject()
		{
			//TODO: Define CanDeleteObject permission in Funcionario
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("FuncionarioDeleteGroup"))
			//	return true;
			//return false;
		}
		#endregion //Authorization Rules

		#region Factory Methods
		private Funcionario()
		{ /* require use of factory method */ }

		public static Funcionario NewFuncionario()
		{
			if (!CanAddObject())
				throw new System.Security.SecurityException("User not authorized to add a Funcionario");
			return DataPortal.Create<Funcionario>();
		}

		public static Funcionario GetFuncionario(int id)
		{
			if (!CanGetObject())
				throw new System.Security.SecurityException("User not authorized to view a Funcionario");
			return DataPortal.Fetch<Funcionario>(new Criteria(id));
		}

		public static void DeleteFuncionario(int id)
		{
			if (!CanDeleteObject())
				throw new System.Security.SecurityException("User not authorized to remove a Funcionario");
			DataPortal.Delete(new Criteria(id));
		}

		public override Funcionario Save()
		{
			if (IsDeleted && !CanDeleteObject())
				throw new System.Security.SecurityException("User not authorized to remove a Funcionario");
			else if (IsNew && !CanAddObject())
				throw new System.Security.SecurityException("User not authorized to add a Funcionario");
			else if (!CanEditObject())
				throw new System.Security.SecurityException("User not authorized to update a Funcionario");

			return base.Save();
		}

		#endregion //Factory Methods

		#region Child Factory Methods
		internal static Funcionario NewFuncionarioChild()
		{
			Funcionario child = new Funcionario();
			child.ValidationRules.CheckRules();
			child.MarkAsChild();
			return child;
		}

		internal static Funcionario GetFuncionario(SafeDataReader dr)
		{
			Funcionario child =  new Funcionario();
			child.MarkAsChild();
			child.Fetch(dr);
			return child;
		}
		#endregion //Child Factory Methods

		#region Data Access

		#region Criteria

		[Serializable()]
		private class Criteria
		{
			public int Id;

			public Criteria(int id)
			{
				this.Id = id;
			}
		}

		#endregion //Criteria

		#region Data Access - Create
		[RunLocal]
		protected override void DataPortal_Create()
		{
			ValidationRules.CheckRules();
		}

		#endregion //Data Access - Create

		#region Data Access - Fetch
		private void DataPortal_Fetch(Criteria criteria)
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				ExecuteFetch(cn, criteria);
			}//using
		}

		private void ExecuteFetch(SqlConnection cn, Criteria criteria)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_GetFuncionario";
				cm.Parameters.AddWithValue("@id", criteria.Id);

				using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
				{
					dr.Read();
					FetchObject(dr);
					ValidationRules.CheckRules();

					//load child object(s)
					FetchChildren(dr);
				}
			}//using
		}

		#endregion //Data Access - Fetch

		#region Data Access - Insert
		protected override void DataPortal_Insert()
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				ExecuteInsert(cn);

				//update child object(s)
				UpdateChildren(cn);
			}//using

		}

		#endregion //Data Access - Insert

		#region Data Access - Update
		protected override void DataPortal_Update()
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				if (base.IsDirty)
				{
					ExecuteUpdate(cn);
				}

				//update child object(s)
				UpdateChildren(cn);
			}//using

		}

		#endregion //Data Access - Update

		#region Data Access - Delete
		protected override void DataPortal_DeleteSelf()
		{
			DataPortal_Delete(new Criteria(_id));
		}

		private void DataPortal_Delete(Criteria criteria)
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				ExecuteDelete(cn, criteria);

			}//using

		}

		private void ExecuteDelete(SqlConnection cn, Criteria criteria)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_DeleteFuncionario";

				cm.Parameters.AddWithValue("@id", criteria.Id);

				cm.ExecuteNonQuery();
			}//using
		}
		#endregion //Data Access - Delete

		#region Data Access - Fetch
		private void Fetch(SafeDataReader dr)
		{
			FetchObject(dr);
			MarkOld();
			ValidationRules.CheckRules();

			//load child object(s)
			if(!this.IsChild)
				FetchChildren(dr);
		}

		private void FetchObject(SafeDataReader dr)
		{
			_id = dr.GetInt32("id");
			_nome = dr.GetString("Nome");
			_telefone = dr.GetInt32("Telefone");
			_rg = dr.GetString("RG");
			_cpf = dr.GetString("CPF");
			_habilitacao = dr.GetString("Habilitacao");
			_matricula = dr.GetString("Matricula");
			_idUsuario = dr.GetInt32("idUsuario");
			_idUsuarioLogin = dr.GetString("idUsuarioLogin");
		}

		private void FetchChildren(SafeDataReader dr)
		{
		}
		#endregion //Data Access - Fetch

		#region Data Access - Insert
		internal void Insert(SqlConnection cn)
		{
			if (!IsDirty) return;

			ExecuteInsert(cn);
			MarkOld();

			//update child object(s)
			UpdateChildren(cn);
		}

		private void ExecuteInsert(SqlConnection cn)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_AddFuncionario";

				AddInsertParameters(cm);

				cm.ExecuteNonQuery();

				_id = (int)cm.Parameters["@id"].Value;
			}//using
		}

		private void AddInsertParameters(SqlCommand cm)
		{
			cm.Parameters.AddWithValue("@Nome", _nome);
			cm.Parameters.AddWithValue("@Telefone", _telefone);
			cm.Parameters.AddWithValue("@RG", _rg);
			cm.Parameters.AddWithValue("@CPF", _cpf);
			cm.Parameters.AddWithValue("@Habilitacao", _habilitacao);
			cm.Parameters.AddWithValue("@Matricula", _matricula);
			cm.Parameters.AddWithValue("@idUsuario", _idUsuario);
			cm.Parameters.AddWithValue("@id", _id);
			cm.Parameters["@id"].Direction = ParameterDirection.Output;
		}
		#endregion //Data Access - Insert

		#region Data Access - Update
		internal void Update(SqlConnection cn)
		{
			if (!IsDirty) return;

			if (base.IsDirty)
			{
				ExecuteUpdate(cn);
				MarkOld();
			}

			//update child object(s)
			UpdateChildren(cn);
		}

		private void ExecuteUpdate(SqlConnection cn)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_UpdateFuncionario";

				AddUpdateParameters(cm);

				cm.ExecuteNonQuery();

			}//using
		}

		private void AddUpdateParameters(SqlCommand cm)
		{
			cm.Parameters.AddWithValue("@id", _id);
			cm.Parameters.AddWithValue("@Nome", _nome);
			cm.Parameters.AddWithValue("@Telefone", _telefone);
			cm.Parameters.AddWithValue("@RG", _rg);
			cm.Parameters.AddWithValue("@CPF", _cpf);
			cm.Parameters.AddWithValue("@Habilitacao", _habilitacao);
			cm.Parameters.AddWithValue("@Matricula", _matricula);
			cm.Parameters.AddWithValue("@idUsuario", _idUsuario);
		}

		private void UpdateChildren(SqlConnection cn)
		{
		}
		#endregion //Data Access - Update

		#region Data Access - Delete
		internal void DeleteSelf(SqlConnection cn)
		{
			if (!IsDirty) return;
			if (IsNew) return;

			ExecuteDelete(cn, new Criteria(_id));
			MarkNew();
		}
		#endregion //Data Access - Delete
		#endregion //Data Access
	}
}
